package com.haircut.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haircut.enums.PayStatus;
import com.haircut.exception.BusinessException;
import com.haircut.mapper.HaircutConsumptionItem;
import com.haircut.mapper.HaircutUserOrder;
import com.haircut.mapper.WechatUser;
import com.haircut.model.req.AdminBuyReq;
import com.haircut.service.HaircutConsumptionItemService;
import com.haircut.mapper.HaircutConsumptionItemMapper;
import com.haircut.service.HaircutUserOrderService;
import com.haircut.service.WechatUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author Administrator
* @description 针对表【t_haircut_consumption_item(消费项目表)】的数据库操作Service实现
* @createDate 2025-10-30 03:33:27
*/
@Service
@RequiredArgsConstructor
public class HaircutConsumptionItemServiceImpl extends ServiceImpl<HaircutConsumptionItemMapper, HaircutConsumptionItem>
    implements HaircutConsumptionItemService {

    private final WechatUserService wechatUserService;
    private final HaircutUserOrderService userConsumptionService;
    @Override
    public void buy(AdminBuyReq buyReq) {
        WechatUser wechatUser = wechatUserService.getByPhone(buyReq.getPhone());
        if(ObjectUtil.isNull(wechatUser)){
            throw new BusinessException("用户不存在");
        }
        if(wechatUser.getBalance().compareTo(buyReq.getAmount())<0){
            throw new BusinessException("余额不足");
        }
        HaircutUserOrder userConsumption = new HaircutUserOrder();
        userConsumption.setUserId(wechatUser.getId());
        userConsumption.setTotalAmount(buyReq.getAmount());
        userConsumption.setPaymentStatus(PayStatus.PAYING.getCode());
        userConsumption.setOrderTime(new Date());
        userConsumption.setPhone(wechatUser.getPhone());
        userConsumptionService.save(userConsumption);
        WechatUser wechatUserUpdate = new WechatUser();
        wechatUserUpdate.setId(wechatUser.getId());
        wechatUserUpdate.setBalance(wechatUser.getBalance().subtract(buyReq.getAmount()));
        wechatUserService.updateById(wechatUserUpdate);
    }
}




